<template>
  <div>
    <card :_Title="$t('deliveryAddress')" />
    <div class="add-box">
      <Form :model="formData" ref="form" label-position="left" :label-width="100" :rules="ruleInline">
        <FormItem :label="$t('recipient')" prop="name">
          <i-input v-model="formData.name" :placeholder="$t('pleaseEnter') + '收件人姓名'" style="width: 600px"></i-input>
        </FormItem>
        <FormItem :label="$t('recipientRegion')" prop="address">
          <span>{{ formData.address || $t("noAddress") }}</span>

          <Button type="default" style="margin-left: 10px" size="small" @click="$refs.map.open()">{{ $t("select")
            }}</Button>
        </FormItem>
        <!-- 新增：国家显示 -->
        <FormItem :label="'国家'">
          <span>{{ formData.country }}</span>
        </FormItem>
        <!-- 新增：省份显示 -->
        <FormItem :label="'省份'">
          <span>{{ formData.province }}</span>
        </FormItem>
        <!-- 新增：城市显示 -->
        <FormItem :label="'城市'">
          <span>{{ formData.city }}</span>
        </FormItem>
        <FormItem :label="'邮编'" prop="addressNo">
          <i-input v-model="formData.addressNo" :placeholder="$t('pleaseEnter') + '邮编'" style="width: 600px"></i-input>
        </FormItem>
        <FormItem :label="'unit number'" prop="detail">
          <i-input v-model="formData.detail" :placeholder="$t('pleaseEnter') + '详细地址'" style="width: 600px"></i-input>
        </FormItem>
        <FormItem :label="$t('phoneNumber')" prop="mobile">
          <i-input v-model="formData.mobile" :placeholder="$t('pleaseEnter') + '收件人手机号'" style="width: 600px"></i-input>
        </FormItem>
        <FormItem :label="'邮箱'" prop="adderEmail">
          <i-input v-model="formData.adderEmail" :placeholder="$t('pleaseEnter') + '邮箱地址'"
            style="width: 600px"></i-input>
        </FormItem>
        <FormItem :label="$t('addressAlias')">
          <i-input v-model="formData.alias" length :maxlength="4" :placeholder="$t('pleaseEnter') + $t('addressAlias')"
            style="width: 600px">
          </i-input>
        </FormItem>
        <FormItem :label="$t('defaultAddress')">
          <i-switch v-model="formData.isDefault" />
        </FormItem>
      </Form>
    </div>
    <div class="mt_20">
      <Button type="primary" class="mr_10" :loading="loading" @click="save">{{ $t("save") }}{{ $t("deliveryAddress")
        }}</Button>
      <Button @click="$router.back()">返回</Button>
    </div>

    <multipleMap ref="map" @callback="getAddress" />
  </div>
</template>

<script>
import card from "@/components/card";

import multipleMap from "@/components/map/multiple-map";
import * as RegExp from "@/plugins/RegExp.js";
import {
  newMemberAddress,
  editMemberAddress,
  getAddrDetail,
} from "@/api/address";
export default {
  name: "AddAddress",
  data() {
    return {
      formData: {
        // 添加地址表单
        isDefault: false,
        country: '', // 新增：国家
        province: '', // 新增：省份
        city: '', // 新增：城市
        adderEmail: '', // 新增：邮箱
      },
      ruleInline: {
        // 验证规则
        name: [
          {
            required: true,
            message: this.$t("pleaseEnter") + "姓名",
            trigger: "blur",
          },
        ],
        address: [
          {
            required: true,
            message: this.$t("pleaseEnter") + "地址",
            trigger: "change",
          },
        ],
        detail: [
          {
            required: true,
            message: this.$t("pleaseEnter") + "详细地址",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: this.$t("pleaseEnter") + "手机号码" },
        ],
        adderEmail: [
          {
            type: 'email',
            message: "请输入正确的邮箱格式",
            trigger: "blur"
          },
        ],
      },
      loading: false, // 加载状态
      mapMsg: {}, // 地图信息
    };
  },
  methods: {
    save() {
      // 保存地址
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(this.formData));
          params.consigneeAddressPath = params.address.replace(/\s/g, ",");
          delete params.address;
          this.loading = true;
          if (this.$route.query.id) {
            editMemberAddress(params)
              .then((res) => {
                if (res.success) {
                  this.loading = false;
                  this.$router.push("/home/MyAddress");
                }
              })
              .catch(() => {
                this.loading = false;
              });
          } else {
            newMemberAddress(params)
              .then((res) => {
                if (res.success) {
                  this.loading = false;
                  this.$router.push("/home/MyAddress");
                }
              })
              .catch(() => {
                this.loading = false;
              });
          }
        }
      });
    },
    getAddrById(id) {
      // 获取地址详情
      getAddrDetail(id).then((res) => {
        if (res.success) {
          console.log(res);
          const data = res.result;
          data.address = res.result.consigneeAddressPath.replace(/,/g, " ");
          this.formData = data;
        }
      });
    },
    getAddress(val) {
      // 获取地图选择信息
      if (val.type === "select") {
        const paths = val.data.map((item) => item.name).join(",");
        const ids = val.data.map((item) => item.id).join(",");
        this.$set(this.formData, "address", paths);
        this.$set(this.formData, "consigneeAddressIdPath", ids);

        // 提取国家、省份、城市信息
        if (val.data && val.data.length > 0) {
          // 遍历地址组件，查找对应的类型
          val.data.forEach(item => {
            // 谷歌地图返回的地址组件包含 types 属性
            if (item.types && Array.isArray(item.types)) {
              // 国家
              if (item.types.includes('country')) {
                this.$set(this.formData, "country", item.name);
                this.$set(this.formData, "addressCountry", item.name);
              }
              // 省份/州
              else if (item.types.includes('administrative_area_level_1')) {
                this.$set(this.formData, "province", item.name);
                this.$set(this.formData, "addressProvince", item.name);
              }
              // 城市
              else if (item.types.includes('locality') || item.types.includes('administrative_area_level_2')) {
                this.$set(this.formData, "city", item.name);
                this.$set(this.formData, "addressCity", item.name);
              }
            } else {
              // 如果没有 types 属性，尝试根据位置判断
              // 假设地址数据按层级排列
              const index = val.data.indexOf(item);
              if (index === 0) { // 第一个元素可能是国家
                this.$set(this.formData, "country", item.name);
                this.$set(this.formData, "addressCountry", item.name);
              } else if (index === 1) { // 第二个元素可能是省份
                this.$set(this.formData, "province", item.name);
                this.$set(this.formData, "addressProvince", item.name);
              } else if (index === 2) { // 第三个元素可能是城市
                this.$set(this.formData, "city", item.name);
                this.$set(this.formData, "addressCity", item.name);
              }
            }
          });

          // 打印日志，方便调试
          console.log("提取的地址信息：", {
            country: this.formData.country,
            province: this.formData.province,
            city: this.formData.city,
            addressCountry: this.formData.addressCountry,
            addressProvince: this.formData.addressProvince,
            addressCity: this.formData.addressCity
          });
        }

        const coord = val.data[val.data.length - 1].center.split(",");
        this.formData.lat = coord[1];
        this.formData.lon = coord[0];
      } else {
        this.$set(this.formData, "address", val.data.addr);
        this.$set(this.formData, "consigneeAddressIdPath", val.data.addrId);
        this.$set(this.formData, "detail", val.data.address);

        // 从地址数据中提取城市、省份、国家信息
        if (val.data.country) {
          this.$set(this.formData, "country", val.data.country);
          this.$set(this.formData, "addressCountry", val.data.country);
        }
        if (val.data.province) {
          this.$set(this.formData, "province", val.data.province);
          this.$set(this.formData, "addressProvince", val.data.province);
        }
        if (val.data.city) {
          this.$set(this.formData, "city", val.data.city);
          this.$set(this.formData, "addressCity", val.data.city);
        }

        this.formData.lat = val.data.position.lat;
        this.formData.lon = val.data.position.lng;
      }
    },
  },
  mounted() {
    const id = this.$route.query.id;
    if (id) this.getAddrById(id);
  },
  components: {
    card,
    multipleMap,
  },
};
</script>

<style scoped lang="scss">
.add-box {
  margin: 40px 0;
}
</style>
